var koa = require('koa')
var app = new koa()
var logger = require('koa-logger')
var json = require('koa-json')
var views = require('koa-views')
var onerror = require('koa-onerror')
var DB = require("./util/DB");

const typeRouter = require("./routes/typesRouter")
const bookRouter = require("./routes/bookRouter")

// error handler
onerror(app);
DB()
// global middlewares
app.use(views('views', {
  root: __dirname + '/views',
  default: 'jade'
}));
app.use(require('koa-bodyparser')());
app.use(json());
app.use(logger());

app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  console.log('%s %s - %s', this.method, this.url, ms);
});

app.use(require('koa-static')(__dirname + '/public'));

// routes definition
app.use(typeRouter.routes(),typeRouter.allowedMethods())
app.use(bookRouter.routes(),bookRouter.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app;
